package com.cole.gx095.service.impl;

import com.cole.gx095.Repository.ExwarehouseRepository;
import com.cole.gx095.service.ExhouseService;
import com.cole.gx095.entity.Exwarehouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class ExhouseServiceImpl implements ExhouseService {
    @Autowired
    ExwarehouseRepository exwarehouseRepository;
    @Override
    public Page<Exwarehouse> findAllBy(Exwarehouse exwarehouse, Integer currentPage, Integer pageSize) {
        currentPage--;
        currentPage = currentPage < 0 ? 0 : currentPage;//page 为页码，数据库从0页开始
        //可以使用重载的 of(int page, int size, Sort sort) 方法指定排序字段
        Pageable pageable = PageRequest.of(currentPage, pageSize);

        Specification<Exwarehouse> purspecification = new Specification<Exwarehouse>() {
            @Override
            public Predicate toPredicate(Root<Exwarehouse> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
//                Join<PurBillgoods,Purchasecontract> join = root.join("purchasecontract", JoinType.LEFT);

                if (exwarehouse.getExNum()!=null&&exwarehouse.getExNum()!="")
                    predicateList.add(criteriaBuilder.equal(root.get("exNum").as(String.class),exwarehouse.getExNum()));
                if (exwarehouse.getStatus()!= null)
                    predicateList.add(criteriaBuilder.equal(root.get("status").as(Date.class),exwarehouse.getStatus()));
                if (exwarehouse.getType()!=null&&!StringUtils.hasLength(exwarehouse.getType()))
                    predicateList.add(criteriaBuilder.equal(root.get("type").as(String.class),exwarehouse.getType()));
                Predicate[] predicates = new Predicate[predicateList.size()];
                return query.where(predicateList.toArray(predicates)).getRestriction();
            }
        };
        return exwarehouseRepository.findAll(purspecification,pageable);//无数据时返回空列表;
    }
}
